package com.jason.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jason.system.common.util.Pager;
import com.jason.system.entity.AdminPermission;
import com.jason.system.entity.AdminRole;
import com.jason.system.entity.User;
import com.jason.system.mapper.PermissionMapper;
import com.jason.system.mapper.RoleMapper;
import com.jason.system.mapper.UserMapper;
import com.jason.system.service.RoleService;
import com.jason.system.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jie
 * @version 1.0
 * success come from self-discipline
 * @date 2021/4/1 21:30
 */

@Service
public class RoleServiceImpl implements RoleService {

  @Resource
  RoleMapper roleMapper;

  @Resource
  UserService userService;

  @Resource
  PermissionMapper permissionMapper;

  @Override
  public List<AdminRole> getAllRole() {
    return roleMapper.getAllRoles();
  }

  @Override
  public Pager<AdminRole> getAllRolePermission(Integer page, Integer size) {
    PageHelper.startPage(page,size);
    List<AdminRole> roleList = roleMapper.getAllRoles();
    for (AdminRole ar : roleList){
      String permissionIds = permissionMapper.getPermissionsByRid(ar.getRId());
      List<Integer> pIds = Arrays.stream(permissionIds.split(",")).map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
      ar.setPermissions(permissionMapper.getPermissionById(pIds));
    }
    PageInfo<AdminRole> rolePageInfo = new PageInfo<>(roleList);
    return new Pager<>(rolePageInfo);
  }

  @Override
  public boolean insertToUserRole(String username, Integer rId) {
    if("".equals(username)||rId ==null){
      return false;
    }
    try {
      // 修改为username和rId
      User user = userService.getUserByName(username);
      if(user.getRole()==null){
        roleMapper.insertToUserRole(user.getUId(),rId);
      }else {
        roleMapper.updateToUserRole(user.getUId(),rId);
      }
      return true;
    }catch (Exception e){
      e.printStackTrace();
      return false;
    }
  }

  @Override
  public boolean deleteUserRole(Integer uId, String rIds) {
    if(uId==null||"".equals(rIds)){
      return false;
    }
    try {
      List<Integer> rIdList = Arrays.stream(rIds.split(",")).map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
      for (Integer rId : rIdList){
        roleMapper.deleteUserRole(uId,rId);
      }
      return true;
    }catch (Exception e){
      e.printStackTrace();
      return false;
    }
  }
}
